package com.ljc.cjgl.service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ljc.cjgl.entitiy.Course;
import com.ljc.cjgl.entitiy.Experence;
import com.ljc.cjgl.form.ExperenceForm;
import com.ljc.cjgl.repository.ExperenceRepository;
import com.ljc.cjgl.security.SysUser;
import com.ljc.cjgl.security.UserUtils;

@Service
public class ExperenceService {
	@Autowired
	private ExperenceRepository experenceDAO;
	@Autowired
	private UserUtils userUtils;
	public Experence findById(Integer id) {
		Optional<Experence> optional = experenceDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	
	
	public List<Experence> findAll(){
		return experenceDAO.findAll();
	}
	
	public Page<Experence> findAll(Specification<Experence> specification,Pageable pageable){
		return experenceDAO.findAll(specification, pageable);
	}


	public synchronized boolean save(ExperenceForm form,String name) {
		try {
			Experence model=new Experence();
			Integer id = form.getId();
			
			if(id!=null) {
				model=findById(id);
				if(userUtils.hasRole("ROLE_STUDENT")&&!userUtils.getUser().getName().equals(model.getCreator())) {
					return false;
				}
			}else {
				model.setCreator(name);
				model.setDate(new Date());
			}
			Integer courseId = form.getCourseId();
			if(courseId!=null) {
				model.setCourse(new Course(courseId));
			}
			BeanUtils.copyProperties(form, model,"id","course","creator","date");
			experenceDAO.save(model);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	
	public synchronized boolean delete(List<Experence> experences) {
		try {
			for (Experence experence : experences) {
				experenceDAO.deleteById(experence.getId());
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}


	public Page<Experence> findAll(Pageable pageable) {
		return experenceDAO.findAll(pageable);
	}


	public List<Course> findCourse() {
		return experenceDAO.findDestinstCourse();
	}


	public List<Experence> findByCourseId(Integer id) {
		return experenceDAO.findByCourseId(id);
	}
	
	

}
